/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ordenar;

import persistencia.Register;
import persistencia.RegisterFile;

/**
 *
 * @author Ivan
 */
public class Mergesort implements MethodOrder{

    public boolean ordenar(RegisterFile reg) {
        long first=0;
        long last=reg.registerCount() -1 ;
        mergesort(reg, first,last);
        return true;
    }

    private void mergesort(RegisterFile reg,long first,long last)
    {
        if (first<last)
        {   long mid=(first + last)/2;//por la division
            mergesort(reg,first,mid);
            mergesort(reg,mid+1,last);
            merge(reg,first,last);
        }

    }

    public void merge(RegisterFile reg,long first,long last)
    {
        Register[] temp=new Register[(int)(last-first)+1];
        long mid=(first + last)/2;
        long i1=0;
        long i2=first;
        long i3=mid+1;
        Register r1 = new Register( reg.tipoDatosAlmacenados() );
        Register r2 = new Register( reg.tipoDatosAlmacenados() );
      
        while (i2<=mid && i3<=last)
        {
            reg.seekRegister(i2);
            reg.read(r1);
            reg.seekRegister(i3);
            reg.read(r2);
            if (r1.compareTo(r2) < 0)
            {
                reg.seekRegister(i2++);
                reg.read(r1);
                temp[(int)i1++]=r1;
            }
            else
            {
                reg.seekRegister(i3++);
                reg.read(r1);
                temp[(int)i1++]=r1;
            }
        }        
        while (i2<=mid || i3<=last)
        {
            if (i2<=mid)
            {
                reg.seekRegister(i2++);
                reg.read(r1);
                temp[(int)i1++]=r1;
            }
            else
            {
                reg.seekRegister(i3++);
                reg.read(r1);
                temp[(int)i1++]=r1;
            }
        }
        for(int i=0;i<i1;i++)
        {
            reg.seekRegister(i+first);
            reg.write(temp[i]);
        }
    }
}
